$(function() {
	// preload images
	preload([
		"//wojianishanghaojiugoujia.gitee.io/public-pages/media/mobile/mobile_v3/icons/stoloto_hover.svg",
		"//wojianishanghaojiugoujia.gitee.io/public-pages/media/mobile/mobile_v3/icons/stoloto.svg"
	]);

	function preload(images) {
		if (typeof document.body == "undefined") return;
		try {
			var div = document.createElement("div");
			var s = div.style;
			s.position = "absolute";
			s.top = s.left = 0;
			s.visibility = "hidden";
			document.body.appendChild(div);
			div.innerHTML =
				'<img src="' + images.join('" /><img src="') + '" />';
			var lastImg = div.lastChild;
			lastImg.onload = function() {
				document.body.removeChild(document.body.lastChild);
			};
		} catch (e) {}
	}

	/* registration */

	var phone = $("#phone"),
		reg_country = $(".reg_country"),
		data_phone = $("#data_phone"),
		phone_code = $(".phone_code"),
		phoneCode = $("#phone_code");

	phone.on("keyup", function() {
		data_phone.val(phone.val().replace(/[^\d+-]/gi, ""));
		if (!reg_country.find(":selected").data("mask")) {
			phone.val(phone.val().replace(/[^\d+-]/gi, ""));
		}
	});
	reg_country.on("change", function() {
		if (reg_country.find(":selected").data("mask") !== null) {
			phone.val("");
			phone.mask(reg_country.find(":selected").data("mask"));
			phone.attr(
				"maxlength",
				reg_country.find(":selected").data("length") + 3
			);
		} else {
			phone.val("");
			phone.unmask();
			phone.attr(
				"maxlength",
				reg_country.find(":selected").data("length")
			);
		}
		phone_code.text(reg_country.find(":selected").data("code"));
		phoneCode.val(reg_country.find(":selected").data("code"));
		data_phone.val(phone.val().replace(/[^\d+-]/gi, ""));
	});

	/* registration */

	/* social login and registration */
	var Social = {
		popup: function(el) {
			var w = window.open(el.href, "", "width=1000,height=650");
		},
		callback: function(service, status) {
			var isLoginned = typeof currentUser != "undefined";
			if (status == "success") {
				document.location.href = document.location.href;
				return;
			}
			if (status == "registration") {
				document.location.href = "/registration";
				return;
			}
			var error = "social." + status;
			var baseUrl = isLoginned ? "/private/data" : "/login";
			document.location.href =
				baseUrl + "?e=" + error + "&service=" + service;
		}
	};

	/* captcha */
	var refrechCaptchaButton = $(".input__actions");
	refrechCaptchaButton.on("click", function() {
		var captcha = refrechCaptchaButton
			.siblings(".input__captcha")
			.find("img");
		var captchaUrlArray = captcha.attr("src").split("=");
		captcha.attr("src", captchaUrlArray[0] + "=" + Math.random());
	});
	/* captcha */

	/* basket */
	var Basket = function(el) {
		this.el = el;
		this.clear = this.el.find(".history__clear");
		this.delete = this.el.find(".history__delete");
		this.ids = [];
		this.emptyPhrase =
			'<div class="title__subtext">Играйте и выигрывайте в лотерейном супермаркете <a href="/">Столото</a></div>';
		this.preloader = $(".loading");
		this.pay = this.el.find(".game__submit");
		this.ticketsArray = ["билет", "билета", "билетов"];
		this.init();
	};

	$.extend(Basket.prototype, {
		init: function() {
			var that = this;
			this.delete.each(function() {
				var $this = $(this);
				that.ids.push($this.data("info").simplyId);
			});
			this.events();
		},
		events: function() {
			this.clear.on("click", $.proxy(this.clearBasket, this));
			this.delete.on("click", $.proxy(this.deleteTicket, this));
			this.pay.on("click", $.proxy(this.payTickets, this));
		},
		clearBasket: function(entity) {
			$("#errors").hide();
			var that = this,
				url = this.clear.data("info").url,
				count = this.clear.data("info").ticketsCount,
				data = {
					ticketsIds: this.ids.join(","),
					ticketsCount: count
				};
			that.preloader.show();
			new AsyncHandler(
				1000,
				url,
				data,
				"POST",
				function(data) {
					that.preloader.hide();
					if (data.status === "ok") {
						that.el.hide();
						$(".title__subtext")
							.text("Корзина пуста")
							.after(that.emptyPhrase);
					}
				},
				function(data) {
					that.preloader.hide();
					$("#errors")
						.show()
						.text(data.error ? data.error : "Что-то пошло не так");
				},
				function(data) {
					that.preloader.hide();
					$("#errors")
						.show()
						.text("Что-то пошло не так");
				}
			).start();
		},
		deleteTicket: function(ev) {
			$("#errors").hide();
			var that = this,
				howMany = "билетов",
				$this = $(ev.currentTarget),
				url = "/actions/cart/remove",
				data = {
					id: $this.data("info").id,
					ticketsCount: $this.data("info").ticketsCount
				};
			delete betsPrice[data.id];
			that.preloader.show();
			new AsyncHandler(
				1000,
				url,
				data,
				"POST",
				function(data) {
					that.preloader.hide();
					if (data.stakesAmount == "0") {
						that.el.hide();
						$(".title__subtext")
							.text("Корзина пуста")
							.after(that.emptyPhrase);
					} else {
						if (
							data.stakesAmount % 10 === 1 &&
							data.stakesAmount !== 11
						) {
							howMany = that.ticketsArray[0];
						} else if (
							data.stakesAmount % 10 > 1 &&
							data.stakesAmount % 10 < 5 &&
							(data.stakesAmount < 11 || data.stakesAmount > 20)
						) {
							howMany = that.ticketsArray[1];
						} else {
							howMany = that.ticketsArray[2];
						}
						that.pay.find("span").text(data.cartSum);
						$(".title__subtext")
							.find("span")
							.text(data.stakesAmount + " " + howMany);
					}
				},
				function(data) {
					that.preloader.hide();
					$("#errors")
						.show()
						.text(data.error ? data.error : "Что-то пошло не так");
				},
				function(data) {
					that.preloader.hide();
					$("#errors")
						.show()
						.text("Что-то пошло не так");
				}
			).start();
		},
		payTickets: function() {
			$("#errors").hide();
			var that = this,
				url = this.pay.data("info");
			/*	identification_required = $("#identification_required");
			if (identification_required) {
				var isBetMaxUnidentSum = false;
				for (key in betsPrice) {
					if (
						betsPrice[key] >=
						parseInt(
							identification_required.data(
								"maxunidentificatedsum"
							)
						)
					) {
						isBetMaxUnidentSum = true;
					}
				}
				var identificationStatus = identification_required.data(
					"identificationstatus"
				);
				if (isBetMaxUnidentSum && identificationStatus != "passed") {
					Finch.Identification.popup(identificationStatus);
					//ga('send', 'pageview', '/virtual/identification/pop-up-payment-is-not-possible');
					return false;
				}
			}*/
			that.preloader.show();
			var self = this;

			withGAdata(function(setGAdata) {
				var data = {};
				setGAdata(data);
                new AsyncHandler(
				1000,
				url,
				data,
				"POST",
				function(data) {
					that.preloader.hide();
				},
				function(data) {
					that.preloader.hide();
					$("#errors")
						.show()
						.text(data.error ? data.error : "Что-то пошло не так");
				},
				function(data) {
					that.preloader.hide();
					$("#errors")
						.show()
						.text("Что-то пошло не так");
				}
			).start();
			});

			
		}
	});

	$(".js-basket").each(function() {
		new Basket($(this));
	});
	/* basket */

	/* check coupon */
	var Coupon = function(el) {
		this.el = el;
		this.combination = [];
		this.maxNumber = this.el.data("maxnumber");
		this.minNumber = this.el.data("minnumber");
		if (
			this.el.hasClass("coupons_game_rapido") ||
			this.el.hasClass("coupons_game_4x20") ||
			this.el.hasClass("coupons_game_5x36plus") ||
			this.el.hasClass("coupons_game_5x50")
		) {
			this.extraNumberCount = [];
			this.validate = function() {
				this.combination.length >= this.minNumber &&
				this.combination.length <= this.maxNumber &&
				!!this.inputs.find("[name=drawing]").val() &&
				this.extraNumberCount.length > 0
					? this.submit.removeAttr("disabled")
					: this.submit.attr("disabled", "disabled");
			};
		}
		this.init();
	};
	$.extend(Coupon.prototype, {
		init: function() {
			this.form = this.el.closest(".form");
			this.inputs = this.form.find(".js-inputs");
			this.submit = this.form.find("[type=submit]");
			this.events();
		},
		events: function() {
			this.el.on("click", $.proxy(this.couponHandler, this));
		},
		couponHandler: function(ev) {
			var target = $(ev.target),
				targetNumber = parseInt(target.text(), 10);
			if (
				target.hasClass("coupons__num") &&
				!target.hasClass("coupons__num_extra")
			) {
				if (target.hasClass("coupons__num_active")) {
					target.removeClass("coupons__num_active");
					this.combination.splice(
						this.combination.indexOf(targetNumber),
						1
					);
				} else {
					if (this.combination.length < this.maxNumber) {
						target.addClass("coupons__num_active");
						this.combination.push(targetNumber);
					}
				}
			} else if (target.hasClass("coupons__num_extra")) {
				if (target.hasClass("coupons__num_active")) {
					target.removeClass("coupons__num_active");
					this.extraNumberCount.splice(
						this.extraNumberCount.indexOf(targetNumber),
						1
					);
				} else {
					if (this.extraNumberCount.length < 8) {
						target.addClass("coupons__num_active");
						this.extraNumberCount.push(targetNumber);
					}
				}
			}
			this.inputs.find("[name=combination]").val(this.combination);
			this.inputs
				.find("[name=extraCombination]")
				.val(this.extraNumberCount);
			this.validate();
		},
		validate: function() {
			this.combination.length >= this.minNumber &&
			this.combination.length <= this.maxNumber &&
			!!this.inputs.find("[name=drawing]").val()
				? this.submit.removeAttr("disabled")
				: this.submit.attr("disabled", "disabled");
		}
	});
	var coupons = [];
	var drawing = $(".js-inputs").find("[name=drawing]");
	var couponsBlocks = $(".js-coupons");

	function replaseNotNumber(input) {
		if (input.value.match(/[^0-9]/g)) {
			input.value = input.value.replace(/[^0-9]/g, "");
		}
	}

	drawing.on("keyup", function() {
		replaseNotNumber(this);
		coupons[
			couponsBlocks
				.filter(function() {
					return $(this).css("display") == "block";
				})
				.index()
		].validate();
	});
	couponsBlocks.each(function() {
		coupons.push(new Coupon($(this)));
	});
	/* check coupon */

	// tabs selector
	$(".js-select").on("change", function() {
		var selectItem = $(this),
			mode = selectItem.data("mode"),
			game = selectItem.find(":selected").val();
		var gameLabel = "game_" + game;
		var gameLastDraws = $("#last_draws").data("lastdraws")[gameLabel];
		$(".last_draws_links." + mode).html("");
		if (gameLastDraws) {
			var links = "";
			gameLastDraws.forEach(function(item, i, arr) {
				links =
					links +
					"<a href='#' data-value='" +
					item.value +
					"'>" +
					item.label +
					"</a>, ";
			});
			$(".last_draws_links." + mode).html(links.slice(0, -2));
		}
		$(".check_form_wrap_" + mode).show();
		$(".check_ticket_game_logo_" + mode)
			.show()
			.attr("src", "//wojianishanghaojiugoujia.gitee.io/public-pages/media/mobile/mobile_v3/icons/logo_" + game + ".svg");
		if (selectItem.find(":selected").data("game") == "game_gzhl") {
			$(".gzhl-2018").show();
		} else {
			$(".gzhl-2018").hide();
		}
		if (selectItem.attr("id") == "gameName") {
			var gt = "#gameTiraj";
		} else {
			var gt = "#gameTiraj2";
		}
		$(".text_about_draw_" + mode).hide();
		if (
			selectItem.find(":selected").data("game") == "game_5x36" ||
			selectItem.find(":selected").data("game") == "game_5x36plus"
		) {
			$(".text_for_" + game + "_" + mode).show();
		}
		if (
			selectItem.find(":selected").data("game") == "game_ny5x36" ||
			selectItem.find(":selected").data("game") == "game_ny6x45"
		) {
			$(gt).prop("disabled", true);
			$(gt).val("1");
			$("#" + gt.substring(1) + "myfieldid").remove();
			$("<input type='hidden' value='1' />")
				.attr("id", gt.substring(1) + "myfieldid")
				.attr("name", "drawing")
				.insertAfter(gt);
		} else {
			$(gt).prop("disabled", false);
			$(gt).val("");
			$("#" + gt.substring(1) + "myfieldid").remove();
		}
		//  urlPart = selectItem.find(':selected').data('game').split('_')[1],
		//  form = selectItem.closest('.form'),
		//  formActionArray = form.attr('action').split('/');
		//formActionArray[1] = urlPart;
		//form.attr('action', formActionArray.join('/'));
		$(".coupons_" + selectItem.find(":selected").data("game"))
			.slideDown(minSpeed)
			.siblings()
			.slideUp(minSpeed, function() {
				if (
					selectItem
						.closest(".form")
						.find(".js-coupons")
						.size() > 0
				) {
					coupons[
						couponsBlocks
							.filter(function() {
								return $(this).css("display") == "block";
							})
							.index()
					].validate();
				}
			});
		$(".check-clear").on("click", function() {
			$(gt).prop("disabled", false);
			$(gt).val("");
			$("#" + gt.substring(1) + "myfieldid").remove();
		});
	});
	$(".last_draws_links").on("click", "a", function() {
		$(this)
			.parent()
			.parent()
			.find("input")
			.val($(this).data("value"));
		return false;
	});

	/* check number */
	var numberForm = $(".js-numberForm"),
		isValid = false,
		submit = numberForm.find("[type=submit]");

	function validate(form) {
		isValid = true;
		var inputs = form.find("input");
		inputs.each(function() {
			var $this = $(this);
			if (!$this.val()) {
				isValid = false;
			}
		});
	}

	numberForm.on("keyup", "input", function(ev) {
		replaseNotNumber(ev.currentTarget);
		validate(numberForm);
		if (isValid) {
			submit.removeAttr("disabled");
		} else {
			submit.attr("disabled", "disabled");
		}
	});
	/* check number */

	/* reset check */
	var formSubmit = $(".js-numberForm").find("[type=submit]");
	var formReset = $(".js-numberForm").find("[type=reset]");
	formReset.on("click", function() {
		formSubmit.attr("disabled", "disabled");
	});
	/* reset check */

	var historyItem = $(".js-history__item");
	historyItem.on("click", function() {
		var $this = $(this);
		!$this.hasClass("history__item_opened")
			? $this.addClass("history__item_opened")
			: $this.removeClass("history__item_opened");
	});

	/* breadcrumbs back */

	var backButton = $(".breadcrumbs .breadcrumbs__back");
	var backPopup = $(".popup_back");

	backButton.on("click", function(ev) {
		var $this = $(this);
		ev.preventDefault();
		if ($this.hasClass("js-backConfirm")) {
			backPopup.addClass("popup_active");
		} else {
			window.history.back();
		}
	});

	backPopup.on("click", function(ev) {
		var $this = $(ev.target);
		if ($this.hasClass("popup_back_ok")) {
			if (
				!document.referrer ||
				document.referrer.startsWith(
					document.location.origin + "/login"
				)
			) {
				location.href = location.origin;
			} else {
				window.history.back();
			}
		} else if ($this.hasClass("popup_back_cancel")) {
			backPopup.removeClass("popup_active");
		}
	});

	/* breadcrumbs back */

	/* download mobile app */

	var UA = navigator.userAgent,
		type = "desktop";
	// Detect banner type (iOS or Android).
	if (
		UA.match(/Windows Phone/i) !== null &&
		UA.match(/Edge|Touch/i) !== null
	) {
		type = "desktop";
	} else if (UA.match(/iPhone|iPod/i) !== null || UA.match(/iPad/)) {
		type = "ios";
	} else if (
		UA.match(/\bSilk\/(.*\bMobile Safari\b)?/) ||
		UA.match(/\bKF\w/) ||
		UA.match("Kindle Fire")
	) {
		type = "desktop";
	} else if (UA.match(/Android/i) !== null) {
		type = "android";
	}

	if (type == "ios") {
		$(".footer__app--ios").show();
		$(".menu__item__app--ios").show();
	} else if (type == "android") {
		$(".footer__app--android").show();
		$(".menu__item__app--android").show();
	} else {
		$(".footer__app--desktop").show();
		$(".menu__item__app--desktop").show();
	}

	/* download mobile app */

	/* one click ticket */

	var oneClickBlock = $(".one-click-games");
	if (oneClickBlock.length) {
		var gameList = oneClickBlock.data("games");
		var gameListWithIndex = [];
		var gameLinks = $(".show", oneClickBlock);
		var visibleLinks = gameLinks;
		var count = 9;

		setZIndex(false);

		function setZIndex(round) {
			gameList.forEach(function(el, ind, arr) {
				gameListWithIndex.push({
					name: el,
					index: round ? ind + 1 : arr.length - ind
				});
			});
		}

		setInterval(function() {
			$(visibleLinks[0]).addClass("to-left");

			var nextLink = $(
				"a[data-number=" + count + "]",
				oneClickBlock
			).addClass("show no-transition");
			var prevLink = visibleLinks[0];
			var leftPosition = Math.round(
				(oneClickBlock.width() - $(prevLink).width()) / 5
			);
			visibleLinks = visibleLinks.slice(1);
			visibleLinks.push(nextLink);
			visibleLinks.each(function(ind, el) {
				$(el).css({
					left: leftPosition * ind + "px",
					zIndex: visibleLinks.length - ind
				});
			});
			if (count == gameList.length) {
				count = 1;
				gameListWithIndex = [];
				setZIndex(true);
			} else {
				count++;
			}
			setTimeout(function() {
				$(prevLink)
					.removeClass("show")
					.removeClass("to-left")
					.removeAttr("z-index")
					.css({ "z-index": "0", left: "115px" });
				nextLink.removeClass("no-transition");
			}, 700);
		}, 2000);
	}

	/* one click ticket */
});
